package com.framework.loippi.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.framework.loippi.service.RedisService;
import com.framework.loippi.support.APIPrincipal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

//	@Resource
//	private CacheService cacheService;

    @Resource
    private RedisService redisService;

    // 不需要登录的接口控制
    private Set<Pattern> freeset = new HashSet<>();
    // session参数名字
    private String sessionName = "sessionId";

    {
        freeset.add(Pattern.compile("/api/category/*"));
        freeset.add(Pattern.compile("/api/agreement/*"));
        freeset.add(Pattern.compile("/api/subscribe/*"));
        freeset.add(Pattern.compile("/api/department/*"));
        freeset.add(Pattern.compile("/api/doctor/*"));
//        freeset.add(Pattern.compile("/api/online/*"));
//        freeset.add(Pattern.compile("/api/patient/*"));
        freeset.add(Pattern.compile("/api/order/*"));
        freeset.add(Pattern.compile("/api/logistics/*"));
        freeset.add(Pattern.compile("/api/work/*"));
        freeset.add(Pattern.compile("/api/auths/*"));
        freeset.add(Pattern.compile("/api/auth/*"));
        freeset.add(Pattern.compile("/api/payCallBack/*"));
        freeset.add(Pattern.compile("/api/article/*"));
        freeset.add(Pattern.compile("/api/index/*"));
        freeset.add(Pattern.compile("/api/common/*"));
        freeset.add(Pattern.compile("/api/swagger/*"));
        freeset.add(Pattern.compile("/api/view/*"));
        freeset.add(Pattern.compile("/api/subscribe/*"));
        freeset.add(Pattern.compile("/api/v1/sms/*"));
        freeset.add(Pattern.compile("/api/t_user/*"));

        freeset.add(Pattern.compile("/api/app_user/check_phone.json"));//验证原手机号
        // 拼团分享页面
        freeset.add(Pattern.compile("/api/user_order/share_group_view.json"));
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        //解决跨域请求问题
        response.setHeader("Access-Control-Allow-Origin", "*"); //针对哪个域名可以访问，*表示所有
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");
        response.addHeader("Access-Control-Max-Age", "1800");//30 min

        String uri = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String authenticationId = request.getHeader(APIPrincipal.PORPERTITY_AUTHENTICATION);
        if (null == authenticationId || "".equals(authenticationId)) {
            // 获取回话ID
            authenticationId = request.getParameter(APIPrincipal.PORPERTITY_AUTHENTICATION);
        }
        request.setAttribute(sessionName, authenticationId);
        // 获取缓存实体
        APIPrincipal principal = redisService.get(authenticationId, APIPrincipal.class);
        HttpSession session = request.getSession();
        session.setAttribute(APIPrincipal.PREFIX_USER_SESSION, principal);
        session.setMaxInactiveInterval(30 * 60);
        // 先检查是否为不需要签名的界面
        for (Pattern pattern : freeset) {
            if (pattern.matcher(uri).find()) {
                return true;
            }
        }
		/*if (SettingUtils.get().getIsDevelopmentEnabled())
		{
			return true;
		}*/

        if (principal != null) {
            return true;
        } else {// 是需要拦截的地址则要判断是否跳转到首页
            Map<String, Object> map = new HashMap<>();
            map.put("code", "11001");
            map.put("message", "登录失效，请重新登录");
            responseJsonMessage(response, map);
            return false;
        }
    }

    private void responseJsonMessage(HttpServletResponse response, Object msg) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.write(JSONObject.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void responseJsonMessage(HttpServletResponse response, String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
